import { Writer } from 'protobufjs/minimal';
import { Message } from 'protobufjs';
import { MessageMapByCmd } from "./Protobuf/protoMappings";

export namespace ProtobufUtil {
    function getPbByCmd(cmdMainId: number, cmdSubId: number, csType: string): any {
        return MessageMapByCmd[`${cmdMainId}_${cmdSubId}_${csType}`];
    }

    export function pbEncode(message: any): Uint8Array {
        let writer = message.constructor.encode(message) as Writer;
        return writer?.finish();
    }
    
    export function pbDecode<T extends Message>(cmdMainId: number, cmdSubId: number, data: Uint8Array): T {
        try {

            let pbType = getPbByCmd(cmdMainId, cmdSubId, "s2c");
            return pbType.decode(data);
        } catch (e) {
            console.error(`pb decode errors error: ${e}`);
        }
    }

}